package cn.lhl.web.controller.system;

import cn.lhl.common.utils.Encrypt;
import cn.lhl.domain.system.Dept;
import cn.lhl.domain.system.Role;
import cn.lhl.domain.system.User;
import cn.lhl.service.system.DeptService;
import cn.lhl.service.system.RoleService;
import cn.lhl.service.system.UserService;
import cn.lhl.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(value = "/system/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping(value = "/list", name = "用户信息分页查询")
    public String findAll(@RequestParam(defaultValue = "1") int page,
                          @RequestParam(defaultValue = "5") int size) {//需要传递两个参数用于分页
        PageInfo allUser = userService.findAll(page, size, companyId);

        model.addAttribute("page", allUser);

        return "system/user/user-list";
    }


    @RequestMapping(value = "/toAdd", name = "去新增页面")
    public String toAdd() {
        //因为新增界面需要所有部门作为选择,所以需要将所有部门查询出来
        List<Dept> deptList = deptService.deptList(companyId);
        model.addAttribute("deptList", deptList);
        return "system/user/user-add";
    }

    @RequestMapping(value = "/toUpdate", name = "去修改页面")
    public String toEdit(String id) {
        //因为修改界面需要所有部门作为选择,所以需要将所有部门查询出来
        List<Dept> deptList = deptService.deptList(companyId);
        model.addAttribute("deptList", deptList);
        //同时也需要User表中的信息
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "system/user/user-update";
    }

    /*@RequestMapping(value = "/edit", name = "保存用户信息")
    public String edit(User user){

        user.setCompanyId(companyId);
        user.setCompanyName(companyName);

        if (StringUtil.isEmpty(user.getId())){
            //新建
            user.setId(UUID.randomUUID().toString());
            user.setPassword(Encrypt.md5(user.getPassword(), user.getEmail()));
            userService.save(user);
        }else {
            //编辑
            userService.update(user);
        }
        return "redirect:/system/user/list.do";
    }*/
    /*@RequestMapping(value = "/edit", name = "保存用户信息")
    public String edit(User user) throws Exception {

        user.setCompanyId(companyId);
        user.setCompanyName(companyName);

        if (StringUtil.isEmpty(user.getId())){
            //新建
            user.setId(UUID.randomUUID().toString());
            String password = user.getPassword();
            user.setPassword(Encrypt.md5(user.getPassword(), user.getEmail()));
            userService.save(user);

            //发送邮件
            String to = user.getEmail();
            String subject = "欢迎来到SaaS-Export大家庭";
            String content = "您使用的SaaS-Export平台通过：http://localhost:8080 进行登录，用户名为："+to+"，密码是："+password;
            MailUtil.sendMsg(to, subject, content);
        }else {
            //编辑
            userService.update(user);
        }
        return "redirect:/system/user/list.do";
    }*/

    @RequestMapping(value = "/edit", name = "保存用户信息")
    public String edit(User user) throws Exception {

        user.setCompanyId(companyId);
        user.setCompanyName(companyName);

        if (StringUtil.isEmpty(user.getId())){
            //新建
            user.setId(UUID.randomUUID().toString());

            String password = user.getPassword();

            user.setPassword(Encrypt.md5(user.getPassword(), user.getEmail()));
            userService.save(user);

            //发送邮件
            String to = user.getEmail();
            String subject = "欢迎来到SaaS-Export大家庭";
            String content = "您使用的SaaS-Export平台通过：http://localhost:8080 进行登录，用户名为："+to+"，密码是："+password;
            //MailUtil.sendMsg(to, subject, content);

            //将邮件内容写入到rabbitMQ中
            /**
             * 两个参数：1、routingKey：队列名称，对应于配置文件中的队列名
             *          2、传入的发送的消息参数
             */

            Map map = new HashMap();
            map.put("to", to);
            map.put("subject", subject);
            map.put("content", content);

            amqpTemplate.convertAndSend("mail.send", map);
        }else {
            //编辑
            userService.update(user);
        }
        return "redirect:/system/user/list.do";
    }

    @RequestMapping(value = "/delete", name = "删除")
    public String delete(String id) {
        userService.delete(id);
        return "redirect:/system/user/list.do";
    }

    @RequestMapping(value = "/roleList", name = "跳转到用户角色分配界面")
    public String roleList(String id) {
        //首先我要知道我改的是哪个用户的权限,根据id查询出角色信息
        User user = userService.findById(id);
        model.addAttribute("user", user);
        //我需要知道所有的角色,通过roleService得到所有的角色(注意该查询需要companyId字段)
        List<Role> roleList = roleService.findAll(companyId);
        model.addAttribute("roleList", roleList);
        //查询出该user所具有的角色(需要嵌套查询,先查出用户有哪些角色id,根据id查询出name)
        List<Role> roleList1 = roleService.findByUserId(id);
        //遍历该集合写成字符串形式
        StringBuilder sb = new StringBuilder();
        for (Role role : roleList1) {
            sb.append(role.getId() + ",");
        }
        String str = sb.toString();
        //System.out.println(str);
        model.addAttribute("userRoleStr", str);
        return "/system/user/user-role";
    }

    @RequestMapping(value = "/changeRole", name = "改变角色,先清空再保存")
    //两个参数user_id,role_id,清空user_id的pe_role_user表中信息,再去赋值
    public String changeRole(String userid, String roleIds) {
        userService.changeRole(userid, roleIds);
        return "redirect:/system/user/list.do";
    }
}
